﻿Imports SdlDotNet.Graphics
Imports SdlDotNet.Graphics.Sprites
Imports System.Drawing
Imports System.Timers

Public Class PopulationMigration
    Implements ITemporaryDrawableEntity

    Private MigrationSprite As AnimatedSprite

    Private WithEvents SpriteTimer As New Timer(1)
    Private CurrentPosition As Point
    Private StartCity As City
    Private DestinationCity As City
    Private AmountOfPeople As Integer

    Public Event NoLongerInUse(ByRef sender As ITemporaryDrawableEntity) Implements ITemporaryDrawableEntity.NoLongerInUse

    Public Sub New(ByVal startCity As City, ByVal destinationCity As City, ByVal amountOfPeople As Integer)
        Me.StartCity = startCity
        Me.DestinationCity = destinationCity
        Me.AmountOfPeople = amountOfPeople

        If (startCity.Position.X >= destinationCity.Position.X) Then
            MigrationSprite = New AnimatedSprite(CommonSurfaces.Instance().PopulationMigrationMovingLeftSurfaces, New Point(0, 0))
        Else
            MigrationSprite = New AnimatedSprite(CommonSurfaces.Instance().PopulationMigrationMovingRightSurfaces, New Point(0, 0))
        End If

        MigrationSprite.Animate = True
        MigrationSprite.Animations.Loop = True

        CurrentPosition = startCity.Position
        SpriteTimer.Start()
        startCity.Health -= amountOfPeople
    End Sub

    Private Sub SpriteTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles SpriteTimer.Elapsed
        If (CurrentPosition.X > DestinationCity.Position.X) Then
            CurrentPosition.X -= 1
        ElseIf (CurrentPosition.X < DestinationCity.Position.X) Then
            CurrentPosition.X += 1
        End If

        If (CurrentPosition.Y > DestinationCity.Position.Y) Then
            CurrentPosition.Y -= 1
        ElseIf (CurrentPosition.Y < DestinationCity.Position.Y) Then
            CurrentPosition.Y += 1
        End If

        If (CurrentPosition = DestinationCity.Position) Then
            ReachedDestination()
        End If
    End Sub

    Private Sub ReachedDestination()
        SpriteTimer.Stop()
        DestinationCity.Health += AmountOfPeople
        RaiseEvent NoLongerInUse(Me)
    End Sub

    Public Sub Dispose() Implements ITemporaryDrawableEntity.Dispose
        MigrationSprite.Surface = Nothing
        MigrationSprite.Dispose()
        SpriteTimer.Dispose()
    End Sub

    Public Sub Draw(ByRef display As SdlDotNet.Graphics.Surface) Implements ITemporaryDrawableEntity.Draw
        display.Blit(MigrationSprite, CurrentPosition)
    End Sub

End Class